import { un } from '@uni-helper/uni-network'
import { useUserInfoStore } from './userInfo'
import { changeOnlineStatusAPI } from '@/apis/changeOnlineStatus'

export const useDriverStatusStore = defineStore('driverStatus', () => {
  const userInfoStore = useUserInfoStore()

  const isOnline = ref(false)

  const setIsOnline = async (val: boolean) => {
    uni.showLoading({ title: '切换中...' })
    const res = await changeOnlineStatusAPI({
      is_online: val ? '1' : '0',
    }, userInfoStore.userInfo!.token)
    uni.hideLoading()
    if (res.data?.code !== 1) {
      uni.showToast({ title: res.data?.msg, icon: 'none' })
      return
    }
    isOnline.value = val
    uni.showToast({ title: isOnline.value ? '已上线' : '已下线' })
  }

  const city = ref('')

  const updateCity = async () => {
    const res = await un.get('https://restapi.amap.com/v3/ip?key=462ecb9c8604997cfbef4552c9744bca')
    city.value = (res.data as any).city
  }

  const location = ref({
    lat: '',
    lng: '',
  })

  const updateLocation = async () => {
    const res = await uni.getLocation()
    location.value.lat = res.latitude.toString()
    location.value.lng = res.longitude.toString()
  }

  return { isOnline, setIsOnline, city, updateCity, location, updateLocation }
})
